package utils;

/**
 * Created by fanzhenyu02 on 2020/2/14.
 */


import org.apache.commons.io.FileUtils;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;


public class FileToBase64 {


    /**
     * <p>将文件转成base64 字符串</p >
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer).replaceAll("\n", "");
    }

    /**
     * <p>将base64字符解码保存文件</p >
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    /**
     * <p>将base64字符保存文本文件</p >
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code, String targetPath) throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    // 先得到keyStore
    private static KeyStore getKeyStore(byte[] pfxData, String password) throws Exception {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new ByteArrayInputStream(pfxData), password.toCharArray());
        return keystore;
    }

    // x509证书 
    public static X509Certificate getX509Certificate(byte[] pfxData, String password) throws Exception {
        X509Certificate x509Certificate = null;
        KeyStore keystore = getKeyStore(pfxData, password);
        Enumeration<String> enums = keystore.aliases();
        String keyAlias = "";
        while (enums.hasMoreElements()) {
            keyAlias = enums.nextElement();
            if (keystore.isKeyEntry(keyAlias)) {
                x509Certificate = (X509Certificate) keystore.getCertificate(keyAlias);
            }
        }
        return x509Certificate;
    }

    // 得到操作员的证书序列号
    public static String getOpertatorSn(String strPfx, String strPassword) throws Exception {
        File pfxFile = new File(strPfx);
        String opertatorSn = null;
        X509Certificate cert = getX509Certificate(FileUtils.readFileToByteArray(pfxFile), strPassword);
        BigInteger serialNumbers = cert.getSerialNumber();
        opertatorSn = serialNumbers.toString(16); // 转十六进制
        System.out.println(opertatorSn);
        return opertatorSn;
    }

    /***
     * 读取*.cer公钥证书文件， 获取公钥证书信息
     * @author xgh
     */
    @Test
    public void testReadX509CerFile() throws Exception {
        try {
            // 读取证书文件
            File file = new File("/Users/vonmax/Downloads/down_doc/temp_save/unionquickpay.unionpay.public.cer");
            InputStream inStream = new FileInputStream(file);
            // 创建X509工厂类
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            //CertificateFactory cf = CertificateFactory.getInstance("X509");
            // 创建证书对象
            X509Certificate oCert = (X509Certificate) cf
                    .generateCertificate(inStream);
            inStream.close();
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
            String info = null;
            // 获得证书版本
            info = String.valueOf(oCert.getVersion());
            System.out.println("证书版本:" + info);
            // 获得证书序列号
            info = oCert.getSerialNumber().toString(16);
            System.out.println("证书序列号:" + info);
            // 获得证书有效期
            Date beforedate = oCert.getNotBefore();
            info = dateformat.format(beforedate);
            System.out.println("证书生效日期:" + info);
            Date afterdate = oCert.getNotAfter();
            info = dateformat.format(afterdate);
            System.out.println("证书失效日期:" + info);
            // 获得证书主体信息
            info = oCert.getSubjectDN().getName();
            System.out.println("证书拥有者:" + info);
            // 获得证书颁发者信息
            info = oCert.getIssuerDN().getName();
            System.out.println("证书颁发者:" + info);
            // 获得证书签名算法名称
            info = oCert.getSigAlgName();
            System.out.println("证书签名算法:" + info);

        } catch (Exception e) {
            System.out.println("解析证书出错！");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            String basePath = "/Users/vonmax/Downloads/";

            String signCert = encodeBase64File(basePath + "mtcert.pfx");
            toFile(signCert, basePath + "signCert_private_key.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    public static void main(String[] args) {
//        try {
//            String signCert = encodeBase64File("/Users/vonmax/Downloads/down_doc/temp_save/prod/trade_modify.pfx");
//            String verifyCert = encodeBase64File("/Users/vonmax/Downloads/down_doc/temp_save/prod/cp.cer");
//
//            toFile(signCert, "/Users/vonmax/Downloads/down_doc/temp_save/prod/signCert.txt");
//            toFile(verifyCert, "/Users/vonmax/Downloads/down_doc/temp_save/prod/verifyCert.txt");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    public static void main(String[] args) throws Exception{
//        String base64CodeStr = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tDQpNSUlFMmpDQ0E4S2dBd0lCQWdJRlFCY3hGMll3RFFZSktvWklodmNOQVFFTEJRQXdXREVMTUFrR0ExVUVCaE1DDQpRMDR4TURBdUJnTlZCQW9NSjBOb2FXNWhJRVpwYm1GdVkybGhiQ0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2DQpjbWwwZVRFWE1CVUdBMVVFQXd3T1EwWkRRU0JCUTFNZ1QwTkJNekV3SGhjTk1UY3dOVEV3TURrd09URTNXaGNODQpNakF3TlRFd01Ea3dPVEUzV2pDQmlERUxNQWtHQTFVRUJoTUNRMDR4RnpBVkJnTlZCQW9NRGtOR1EwRWdRVU5UDQpJRTlEUVRNeE1STXdFUVlEVlFRTERBcERSa05CSUU5RFFUTXhNUmt3RndZRFZRUUxEQkJQY21kaGJtbDZZWFJwDQpiMjVoYkMweU1UQXdMZ1lEVlFRRERDZERSa05CUU9TNHJlV2J2ZW1UdHVpQmxFQk9PVEV6TVRBd01EQTNNell5DQpNems0T1RCVVFERXdnZ0VpTUE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6TlRrekxtTnliREFPQmdOVkhROEJBZjhFQkFNQ0E4Z3dIUVlEDQpWUjBPQkJZRUZGWHJ5WXBjeldrUlJVUTkxeXFCZi9sTlZkS2xNQjBHQTFVZEpRUVdNQlFHQ0NzR0FRVUZCd01DDQpCZ2dyQmdFRkJRY0RCREFOQmdrcWhraUc5dzBCQVFzRkFBT0NBUUVBcTU3bzhPSzBWZjJkeUhlUURFNEtaWHZKDQpQL3gxNEt2KzZDWjhFREtsZXhBc0NxYUFOUUZ5ZzVHWUQyVUd1RUJuT2txbjFodkxzeVdRaVI3R2pMcVpEbDd5DQp1emJTaW9SbWROUTBPTzVLNExobHBORU5iSFZISTJyVWRhMngvTDVYdUd2R1F1ZHkzKytyaVFEdzF6RjlVajhlDQpYZFMzZ0U1U0lMTmVKbmdERUtUV05WN2NpUnAvQVFqclFtbjFnRks0bnpDdkczK01pS3BTNzVGcHBZWWRxUVN1DQowZ21SbU5IeityVmpkYWVXZVVQQ05RR1h1ek1VM2p2NldkS3hVbmlvekk3VW1IQk01dU1CbndkQklQb1dDd3c4DQo5aEZjRW9sbllSaWVCTGdPWTcrbUZRWkh2MXBKcktPM2R3eHkrVGxVazdpMUIwaVpEUVhQandPMFZacmZOUT09DQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0t";
//
//        decoderBase64File(base64CodeStr, "/Users/vonmax/Downloads/down_doc/temp_save/unionquickpay.unionpay.public.cer");
//
//    }

//    public static void main(String[] args) {
//        try {
//            String signCert = encodeBase64File("/Users/vonmax/Downloads/1527027541_20200408_cert/apiclient_cert.p12");
//            toFile(signCert, "/Users/vonmax/Downloads/1527027541.txt");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


//    public static void main(String[] args) throws Exception{
//
//        System.out.println(getOpertatorSn("/Users/vonmax/Downloads/down_doc/temp_save/unionquickpay.mt.private.pfx", "111111"));
//    }

}

